/*************************************************************************
    > File Name: client.cpp
    > Author: Lancer
    > Mail: 18826075768@163.com
************************************************************************/

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/shm.h>
#include "shm_com.h"

using namespace std;

int main(){
    int id;
    srand((unsigned int)getpid());
    id = shmget((key_t)1234, sizeof(struct shared_use_st), 0666 | IPC_CREAT);
    if(id == -1){
        fprintf(stderr, "shmget failed!\n");
        exit(EXIT_FAILURE);
    }
    void* shared_memory = (void*)0;
    shared_memory = shmat(id, (void*)0, 0);
    if(shared_memory == (void*)-1){
        fprintf(stderr, "shmat failed!\n");
        exit(EXIT_FAILURE);
    }

    printf("Memory attached at %X\n", (long)shared_memory);
    struct shared_use_st* stuff;
    stuff = (shared_use_st*)shared_memory;
    stuff->written = 0;
    int ret = 1;
    while(ret){
        if(stuff->written){
            printf("you wrote: %s", stuff->text);
            sleep(rand() % 4);
            stuff->written = 0;
            if(strncmp(stuff->text, "end", 3) == 0){
                ret = 0;
            }
        }
    }

    if(shmdt(shared_memory) == -1){
        fprintf(stderr, "shmdt failed!\n");
        exit(EXIT_FAILURE);
    }
    if(shmctl(id, IPC_RMID, 0) == -1){
        fprintf(stderr, "shmctl failed!\n");
        exit(EXIT_FAILURE);
    }

    exit(EXIT_SUCCESS);
}